/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.kimstore.gui.customer;

import com.kimstore.bean.Customer;
import com.kimstore.bean.Item;
import com.kimstore.bean.Order;
import com.kimstore.factory.DaoFactory;
import com.kimstore.main.controller.CustomerTabController;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Administrator
 */
public class ViewCustomerController {

    private CustomerTabController parentController;

    private ViewCustomerWindow window;
    
    private Customer customer;
    
    public ViewCustomerController(CustomerTabController parentController, String customerName) {
        this.parentController = parentController;
        
        customer = DaoFactory.getInstance().getCustomerDao().findByName(customerName);
    }
    
    public void displayWindow(){
        this.window = new ViewCustomerWindow(this);
        
        List<Item> items = new ArrayList<Item>();
        
        for(Item item: DaoFactory.getInstance().getItemDao().getCustomerPurchases(customer)) {
            items.add(item);
        }
        
        window.populateWindow(customer, items);
        window.showWindow();
    }
    
    public void fromWindow(String customerName, String cellphoneNumber, String address){
        customer.setName(customerName);
        customer.setPhoneNumber(cellphoneNumber);
        customer.setAddress(address);
        DaoFactory.getInstance().getCustomerDao().saveOrUpdate(customer);
        
        parentController.createViewCustomerControllerCallback();
    }
    
    public void validate(String name) throws Error {
        if(name == null || name.isEmpty()) {
            throw new Error("<html><b>Customer Name</b> has not been filled up.</html>");
        }
        
        if(!customer.getName().equals(name)) {
            boolean exists = DaoFactory.getInstance().getCustomerDao().existsName(name);

            if(exists) {
                throw new Error("<html><b>Customer Name</b> has already been taken.</html>");
            }
        }
    }
}
